﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Net;

namespace SMS_Server
{
    public static class Global
    {

        #region public static variables

        public static string Licensed_to;

        public static string CompanyName;

        public static string Email;

        public static string SerialNumber;

        public static bool IsTrial;

        public static DateTime StartDate;

        public static DateTime ExpiryDate;

        public static bool IsValidSerial;

        public static string IMEI;

        public static string ProductID="SMSSERVER2011.13";
        public static string[] AllowedCountryCodes = null; //valid country codes for the modem
        public static GSMManager DeviceManager = new GSMManager();
        public static List<GSMModem> Devices = new List<GSMModem>();//List of devices
        public static List<SMSMessage> Inbox = new List<SMSMessage>();//List of messages to be processed
        public static List<SMSMessage> Outbox = new List<SMSMessage>();//List of messages to be sent
        public static Dictionary<string, Function> Tasks = new Dictionary<string, Function>();//List of available tasks

        public static bool ShuttingDown = false;

        #endregion

        #region Public static methods

        /// <summary>
        /// Reload the device list
        /// </summary>
        public static void Refresh_DeviceList()
        {
            GSMManager Temp_Device_Manager = new GSMManager();
            string[] PortNames = SerialPort.GetPortNames();
            string TempIMEIList = "";

            Devices.Clear();
            foreach (string s in PortNames)
            {
                try
                {
                    if (Temp_Device_Manager.SMSConfig(s))
                    {
                        string DeviceData = Temp_Device_Manager.DeviceIdentity;
                        if (Temp_Device_Manager.Manufacturer == "" || Temp_Device_Manager.Model == "" || Temp_Device_Manager.IMEI == "")
                        {
                            Temp_Device_Manager.Close();
                            continue;
                        }
                        else
                        {
                            if (TempIMEIList.IndexOf(Temp_Device_Manager.IMEI) >= 0)
                            {
                                Temp_Device_Manager.Close();
                                continue;
                            }
                            GSMModem device = new GSMModem(Temp_Device_Manager.Manufacturer + " " + Temp_Device_Manager.Model, s, Temp_Device_Manager.Model, Temp_Device_Manager.IMEI);
                            device.PhoneNumber = Temp_Device_Manager.MyNumber;
                            Devices.Add(device);
                            if (TempIMEIList != "") TempIMEIList += ", ";
                            TempIMEIList += Temp_Device_Manager.IMEI;
                        }
                        Temp_Device_Manager.Close();
                    }
                }
                catch(Exception ex)
                {
                    System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
                    el.Log = "Application";
                    el.MachineName = ".";
                    el.Source = "SMS Server";
                    el.WriteEntry("Error refreshing devices: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);

                    continue;
                }
            }
        }

        public static string GetUsageDatabaseName()
        {
            return "Usages";
        }

        public readonly static string DatabasePassword = "Agl#@463687";

        public static string GetConfigurationDatabaseName()
        {
            return "Config";
        }

        public static void SendSMS(string to, string data)
        {
            if (to.Substring(0, 2) == "00") to = "+" + to.Substring(2);
            if (AllowedCountryCodes != null)
            {
                bool isAllowed = false;
                foreach (string s in AllowedCountryCodes)
                {
                    if (to.IndexOf(s) == 0)
                    {
                        isAllowed = true;
                        break;
                    }
                }
                if (!isAllowed) return;
            }
            data = data.Replace("\n", " ");
            data = data.Replace("[", "").Replace("]", "");
            SMSMessage sms = new SMSMessage(to, data);
            Outbox.Add(sms);
        }

        public static void SendEmail(string to, string from, string subject, string data)
        {
            from = "Onuprova SMS Server<smsserver@onuprova.com>";
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(from, to);
            mail.Subject = subject;
            mail.Body = data;
            mail.IsBodyHtml = true;

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("", 587);
            smtp.UseDefaultCredentials = false;
            System.Net.NetworkCredential credential = new System.Net.NetworkCredential("", "");
            smtp.Credentials = credential;
            try
            {
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
                el.Log = "Application";
                el.MachineName = ".";
                el.Source = "SMS Server";
                el.WriteEntry("Error while sending e-mail:" + ex.Message, System.Diagnostics.EventLogEntryType.Information);
            }
        }

        public static System.Net.IPAddress GetDefaultIP()
        {
            string s = System.Net.Dns.GetHostName();
            System.Net.IPAddress[] ips = System.Net.Dns.GetHostEntry(s).AddressList;
            System.Net.IPAddress Ip = ips[0];
            foreach (System.Net.IPAddress i in ips)
            {
                string ipaddress = i.ToString();
                if (ipaddress.IndexOf('.') < 0) continue;
                Ip = i;
            }
            return Ip;
        }

        public static void IncreamentUsages(string functionName)
        {

        }

        private static bool SaveBack()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            if (path[path.Length - 1] == '\\') path = path.Substring(0, path.Length - 1);
            try
            {
                //string MachineID = MachineIdentity.GetMachineIdentity();
                FileStream Sourcefs = new FileStream(path + "\\App_data\\ManageConfig.sdf", FileMode.Open, FileAccess.Read);
                FileStream Destinationfs = new FileStream(path + "\\config\\config.src", FileMode.Create, FileAccess.Write);

                int counter = 0;
                long totall = Sourcefs.Length;
                long tillnow = 0;
                byte[] buffer = new byte[1024];

                //FileSecurity file_security = new FileSecurity();

                while (true)
                {
                    counter = Sourcefs.Read(buffer, 0, buffer.Length);
                    if (counter == 0) break;

                    if (counter == buffer.Length)
                    {
                        //byte[] newBuff = file_security.DeltaMultiply(buffer, MachineID);
                        Destinationfs.Write(buffer, 0, counter);
                    }
                    else
                    {
                        byte[] secbuff = new byte[counter];
                        for (int i = 0; i < counter; i++)
                        {
                            secbuff[i] = buffer[i];
                        }
                        //byte[] newBuff = file_security.DeltaMultiply(secbuff, MachineID);
                        Destinationfs.Write(secbuff, 0, counter);
                    }
                    tillnow += counter;
                }
                Destinationfs.Close();
                Sourcefs.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
        
        #endregion

    }
}
